package com.file.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.file.service.FileService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;


@Controller
public class FileController {

    @Reference
    private FileService fileService;

    @RequestMapping("/html")
    public String getHtml() {
        return "/file/list.html";
    }


    @ResponseBody
    @RequestMapping("/getAllChildrenFileName")
    public String getAllChildrenFileName(@RequestParam(defaultValue = "C:\\") String path,String orderby,boolean desc) {
        List list = fileService.getAllChildrenFileName(path,orderby,desc);
        return JSONObject.toJSONString(list);
    }

    @RequestMapping("/showPic")
    public void showPic(String path, HttpServletResponse response) throws Exception {
        //读取路径下面的文件
        File file = new File(path);
        String gs = file.getName().split("\\.")[1];
        response.setContentType("image/" + gs);
        //读取指定路径下面的文件
        try (InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
             OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());) {
            //创建存放文件内容的数组
            byte[] buff = new byte[1024];
            //所读取的内容使用n来接收
            int n;
            //当没有读取完时,继续读取,循环
            while ((n = inputStream.read(buff)) != -1) {
                //将字节数组的数据全部写入到输出流中
                outputStream.write(buff, 0, n);
            }
            //强制将缓存区的数据进行输出
            outputStream.flush();
        }
    }

}
